// pages/transaction/transaction.ts
import { MerchantAPI } from '../../utils/api'

interface Transaction {
  flowId: number;
  flowNo: string;
  flowType: number;  // 1-收入，2-支出
  businessType: number;
  businessName: string;
  amount: number;
  createdAt: string;
}

/**
 * 业务类型映射
 */
const BUSINESS_TYPE_MAP: { [key: number]: string } = {
  1: '订单收入',
  2: '退款支出',
  3: '提现',
  4: '平台服务费',
  5: '营销费用',
  6: '罚款',
  7: '保证金',
  8: '其他'
};

interface TransactionPageData {
  statusBarHeight: number;
  income: string;
  incomeGrowth: string;
  expense: string;
  expenseGrowth: string;
  categories: any[];
  tabs: string[];
  activeTab: number;
  transactions: any[];
  page: number;
  pageSize: number;
  hasMore: boolean;
  loading: boolean;
}

Page({
  data: {
    statusBarHeight: 0,
    income: '0.00',
    incomeGrowth: '0',
    expense: '0.00',
    expenseGrowth: '0',
    categories: [],
    tabs: ['全部', '收入', '支出'],
    activeTab: 0,
    transactions: [],
    page: 1,
    pageSize: 20,
    hasMore: true,
    loading: false
  } as TransactionPageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0
    });
    
    this.loadTransactions();
  },

  /**
   * 加载交易记录列表
   */
  async loadTransactions(isRefresh = false) {
    if (this.data.loading) return;
    
    if (isRefresh) {
      this.setData({
        page: 1,
        transactions: [],
        hasMore: true
      });
    }
    
    this.setData({ loading: true });
    
    try {
      // 根据activeTab确定flowType
      let flowType: number | undefined = undefined;
      if (this.data.activeTab === 1) {
        flowType = 1;  // 收入
      } else if (this.data.activeTab === 2) {
        flowType = 2;  // 支出
      }
      
      // 构建请求参数，过滤掉undefined值
      const params: any = {
        pageNum: this.data.page,
        pageSize: this.data.pageSize
      };
      
      // 只有当flowType有值时才添加到参数中
      if (flowType !== undefined) {
        params.flowType = flowType;
      }
      
      const response = await MerchantAPI.getFinanceFlowList(params);
      
      if (response.code === 200) {
        // 兼容不同的返回格式：data.list 或 rows
        const dataList = response.data?.list || response.rows || [];
        
        const newTransactions = dataList.map((item: Transaction) => {
          // 优先使用 businessName，如果没有则根据 businessType 映射
          let businessName = item.businessName;
          if (!businessName && item.businessType) {
            businessName = BUSINESS_TYPE_MAP[item.businessType] || '其他';
          }
          // 如果还是没有，则使用默认值
          if (!businessName) {
            businessName = item.flowType === 1 ? '收入' : '支出';
          }
          
          return {
            id: item.flowId,
            flowNo: item.flowNo,
            title: businessName,
            time: item.createdAt,
            amount: (item.flowType === 1 ? '+' : '-') + '¥' + this.formatMoney(item.amount),
            type: item.flowType === 1 ? 'income' : 'expense',
            businessType: item.businessType
          };
        });
        
        const allTransactions = isRefresh ? newTransactions : [...this.data.transactions, ...newTransactions];
        
        this.setData({
          transactions: allTransactions,
          page: this.data.page + 1,
          hasMore: newTransactions.length >= this.data.pageSize
        });
      }
    } catch (error) {
      console.error('加载交易记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 格式化金额
   */
  formatMoney(amount: number): string {
    return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  },

  goBack() {
    wx.navigateBack();
  },

  showMonthPicker() {
    wx.showActionSheet({
      itemList: ['本月', '上月', '最近3个月'],
      success: (res) => {
        wx.showToast({
          title: '已选择: ' + ['本月', '上月', '最近3个月'][res.tapIndex],
          icon: 'none'
        });
        // 可以根据选择的时间范围重新加载数据
      }
    });
  },

  /**
   * 切换Tab
   */
  switchTab(e: any) {
    const index = e.currentTarget.dataset.index;
    if (index === this.data.activeTab) return;
    
    this.setData({
      activeTab: index,
      page: 1,
      transactions: [],
      hasMore: true
    });
    
    this.loadTransactions(true);
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadTransactions();
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadTransactions(true);
    wx.stopPullDownRefresh();
  },

  /**
   * 查看交易详情
   */
  async viewDetail(e: any) {
    const flowId = e.currentTarget.dataset.id;
    
    try {
      const response = await MerchantAPI.getFinanceFlowDetail(flowId);
      
      if (response.code === 200 && response.data) {
        const flow = response.data;
        
        // 获取业务类型名称
        let businessName = flow.businessName;
        if (!businessName && flow.businessType) {
          businessName = BUSINESS_TYPE_MAP[flow.businessType] || '其他';
        }
        if (!businessName) {
          businessName = flow.flowType === 1 ? '收入' : '支出';
        }
        
        // 格式化详情内容
        let content = `流水号：${flow.flowNo}\n`;
        content += `业务类型：${businessName}\n`;
        content += `金额：${flow.flowType === 1 ? '+' : '-'}¥${this.formatMoney(flow.amount)}\n`;
        content += `时间：${flow.createdAt}`;
        
        if (flow.remark) {
          content += `\n备注：${flow.remark}`;
        }
        
        wx.showModal({
          title: '交易详情',
          content: content,
          showCancel: false
        });
      }
    } catch (error) {
      console.error('加载交易详情失败:', error);
      wx.showToast({
        title: '加载详情失败',
        icon: 'none'
      });
    }
  }
});
